package per.turtle.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import per.turtle.common.core.web.controller.BaseController;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.core.web.page.TableDataInfo;
import per.turtle.common.excel.annotation.ResponseExcel;
import per.turtle.common.log.annotation.Log;
import per.turtle.common.log.enums.BusinessType;
import per.turtle.common.security.annotation.PreAuthorize;
import per.turtle.system.entity.SysRole;
import per.turtle.system.entity.SysUser;
import per.turtle.system.entity.SysUserRole;
import per.turtle.system.service.ISysRoleService;
import per.turtle.system.service.ISysUserService;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author turtle
 */
@AllArgsConstructor
@Api(value = "role", tags = {"role_角色管理模块"})
@RequestMapping("role")
@RestController
public class SysRoleController extends BaseController {

    private final ISysRoleService roleService;

    private final ISysUserService userService;

    @ApiOperation(value = "新增角色", notes = "新增角色")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping("add")
    @PreAuthorize(hasPermission = "system:role:add")
    public CommonResult<Void> add(@Validated @RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            return CommonResult.error("新增角色【" + role.getRoleName() + "】失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return CommonResult.error("新增角色【" + role.getRoleName() + "】失败，角色权限已存在");
        }
        return result(roleService.insertRole(role));

    }

    @ApiOperation(value = "查询已分配用户角色列表", notes = "查询已分配用户角色列表")
    @PostMapping("authUser/allocatedList")
    @PreAuthorize(hasPermission = "system:role:list")
    public TableDataInfo<SysUser> allocatedList(@RequestBody SysUser user) {
        List<SysUser> list = startPage(s -> userService.selectAllocatedList(user));
        return getDataTable(list);
    }

    @ApiOperation(value = "取消授权用户", notes = "取消授权用户")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PreAuthorize(hasPermission = "system:role:edit")
    @PutMapping("authUser/cancel")
    public CommonResult<Void> cancelAuthUser(@RequestBody SysUserRole userRole) {
        return result(roleService.deleteAuthUser(userRole));
    }

    @ApiOperation(value = "批量取消授权用户", notes = "批量取消授权用户")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PreAuthorize(hasPermission = "system:role:edit")
    @PutMapping("authUser/cancelAll")
    public CommonResult<Void> cancelAuthUserAll(String roleId, String[] userIds) {
        return result(roleService.deleteAuthUsers(roleId, userIds));
    }

    @ApiOperation(value = "状态修改", notes = "状态修改")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermission = "system:role:edit")
    @PutMapping("changeStatus")
    public CommonResult<Void> changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        return result(roleService.updateRoleStatus(role));
    }

    @ApiOperation(value = "修改保存数据权限", notes = "修改保存数据权限")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermission = "system:role:edit")
    @PutMapping("dataScope")
    public CommonResult<Void> dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        return result(roleService.authDataScope(role));
    }

    @ApiOperation(value = "修改保存角色", notes = "修改保存角色")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermission = "system:role:edit")
    @PutMapping("edit")
    public CommonResult<Void> edit(@Validated @RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        if (!roleService.checkRoleNameUnique(role)) {
            return CommonResult.error("修改角色【" + role.getRoleName() + "】失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return CommonResult.error("修改角色【" + role.getRoleName() + "】失败，角色权限已存在");
        }
        return result(roleService.updateRole(role));
    }

    @ApiOperation(value = "导出角色", notes = "导出角色")
    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PostMapping("export")
    @PreAuthorize(hasPermission = "system:role:export")
    @ResponseExcel("角色管理")
    public List<SysRole> export(HttpServletResponse response, @RequestBody SysRole role) {
        return roleService.selectRoleList(role);
    }

    @ApiOperation(value = "根据角色编号获取详细信息", notes = "根据角色编号获取详细信息")
    @GetMapping("{roleId}")
    @PreAuthorize(hasPermission = "system:role:query")
    public CommonResult<SysRole> getInfo(@PathVariable String roleId) {
        return CommonResult.success(roleService.selectRoleById(roleId));
    }

    @ApiOperation(value = "角色列表或分页", notes = "角色列表或分页（区别于是否传入分页参数）")
    @PostMapping("list")
    @PreAuthorize(hasPermission = "system:role:list")
    public TableDataInfo<SysRole> list(@RequestBody SysRole role) {
        List<SysRole> list = startPage(s -> roleService.selectRoleList(role));
        return getDataTable(list);
    }

    @ApiOperation(value = "获取角色选择框列表", notes = "获取角色选择框列表")
    @GetMapping("optionSelect")
    @PreAuthorize(hasPermission = "system:role:query")
    public CommonResult<List<SysRole>> optionSelect() {
        return CommonResult.success(roleService.selectRoleAll());
    }

    @ApiOperation(value = "删除角色", notes = "删除角色")
    @DeleteMapping("{roleIds}")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @PreAuthorize(hasPermission = "system:role:remove")
    public CommonResult<Void> remove(@PathVariable List<String> roleIds) {
        return result(roleService.deleteRoleByIds(roleIds));
    }

    @ApiOperation(value = "批量选择用户授权", notes = "批量选择用户授权")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PreAuthorize(hasPermission = "system:role:edit")
    @PutMapping("authUser/selectAll")
    public CommonResult<Void> selectAuthUserAll(String roleId, String[] userIds) {
        return result(roleService.insertAuthUsers(roleId, userIds));
    }

    @ApiOperation(value = "查询未分配用户角色列表", notes = "查询未分配用户角色列表")
    @PostMapping("authUser/unallocatedList")
    @PreAuthorize(hasPermission = "system:role:list")
    public TableDataInfo<SysUser> unallocatedList(@RequestBody SysUser user) {
        List<SysUser> list = startPage(s -> userService.selectUnallocatedList(user));
        return getDataTable(list);
    }

}